#include "stdafx.h"
#include "ErrorLogger.h"

ErrorLogger* ErrorLogger::m_error_logger = nullptr;
std::ofstream ErrorLogger::m_log_file;
std::string ErrorLogger::m_log_path;

ErrorLogger::ErrorLogger()
{
    GetLogPath();
    CreateLogFile();
}

ErrorLogger::~ErrorLogger()
{
    m_log_file.close();
}

void ErrorLogger::Initialize()
{
    if (m_error_logger == nullptr)
    {
        m_error_logger = new ErrorLogger();
    }
}

void ErrorLogger::WriteLog(const std::string& fun_name, const std::string& error_message)
{
    std::string local_time;
    ErrorLogger::GetInstance()->GetLocalTime(local_time);

    std::string log_message;
    log_message.append(local_time);
    log_message.append(" ");
    log_message.append(fun_name);
    log_message.append(": ");
    log_message.append(error_message);

    m_log_file << log_message << std::endl;
}

ErrorLogger* ErrorLogger::GetInstance()
{
    ErrorLogger::Initialize();

    return m_error_logger;
}

void ErrorLogger::GetLogPath()
{
    char file_path[MAX_PATH + 1];
    ::GetModuleFileName(NULL, file_path, MAX_PATH);
    (_tcsrchr(file_path, _T('\\')))[1] = 0;

    std::string local_time;
    GetLocalTime(local_time);

    m_log_path.clear();
    m_log_path.append(file_path);
    m_log_path.append("ErrorLog");
    m_log_path.append(local_time);
    m_log_path.append(".log");
}

void ErrorLogger::GetLocalTime(std::string& local_time)
{
    local_time.clear();

    time_t t = time(0);
    tm tm;
    localtime_s(&tm, &t);

    char temp[MAX_PATH + 1];
    _itoa_s(tm.tm_year + 1900, temp, 10);
    local_time.append(temp);
    local_time.append("-");
    _itoa_s(tm.tm_mon, temp, 10);
    local_time.append(temp);
    local_time.append("-");
    _itoa_s(tm.tm_mday, temp, 10);
    local_time.append(temp);
    local_time.append("-");
    _itoa_s(tm.tm_hour, temp, 10);
    local_time.append(temp);
    local_time.append("-");
    _itoa_s(tm.tm_sec, temp, 10);
    local_time.append(temp);
    local_time.append("-");
    _itoa_s(tm.tm_min, temp, 10);
    local_time.append(temp);
}

void ErrorLogger::CreateLogFile()
{
    m_log_file.open(m_log_path, std::ios::out | std::ios::app);
    if (!m_log_file.is_open())
    {
        return;
    }

    m_log_file << "Create success!" << std::endl;
}